var app = angular.module("payApp", []);
var uid, id, money = 0, shid, trade_name,addressId,orderId;
var paytype = 1,
	ptype = '',
	pays = {},
	url = '',
	w = null, 
	orderid;
var cur_statu;
app.controller("payController", function($scope, $http) {
	$scope.goods_num = 1;
	$scope.initView = function($id, $uid) {
		uid = $uid;
		id = $id;
		$http({
			method: 'post',
			url: apiRoot,
			data: {
				action: 'Orderid.initial',
				id: $id,
				uid: $uid,
				ddid:orderId
			}
		}).then(function successCallback(response) {
			var info = response.data.data;
			$scope.goods = info.goods //商品的数据
			$scope.addr = info.addr //地址数据
			$scope.addressId = info.addr.id;
			addressId = info.addr.id;
			$scope.goodsId = info.goods.id;  
			$scope.shid = info.goods.uid;
			money = info.goods.price;
			$scope.price = money;
			//trade_name=response.data.data.goods.good_name;
			$scope.good_name = info.goods.good_name;
			plus.nativeUI.closeWaiting();
		}, function errorfunction(e) {
			console.log(JSON.stringify(e));
			plus.nativeUI.closeWaiting();
		})
	}
	
	$scope.payInitial = function(){ 
		if(addressId == undefined){mui.toast('请添加收货地址');return}
		var channel = $("input[type=radio]:checked").val();
		$http({
			method: 'post',
			url: apiRoot,
			data: {
				action: 'Orderid.payChannel',
				uid: uid,
				channel: channel,
				money: money,
				num: $('#num').val(),
				trade_name: $scope.good_name,
				goodsid: id,
				address:addressId,  
				shid: $scope.shid
			}
		}).then(function successCallback(response) {
			plus.nativeUI.closeWaiting();
			var res = response.data.data;
			console.log(JSON.stringify(res));
			orderid = res.ddid;
			money = res.money;  
			trade_name = res.trade_name;
			payment();
		}, function errorfunction(e) {
			console.log(e);
		})
	}
	
	$scope.create_address = function(){
		openNewPage('my_address.html');
	}
	//支付成功后改变订单状态
//	$scope.send_prepayid = function(orderid,cur_prepayid){
//		$http({
//			method: 'post',
//			url: apiRoot,
//			data: {
//				action: 'orderCallback',
//				orderid: orderid,
//				prepayid: cur_prepayid
//			}
//		}).then(function successFun(result) {
//			console.log(JSON.stringify(result.data.data));
//		}, function errorFun(e) {
//			console.log(JSON.stringify(e));
//		})
//	}
})


//支付类型
$("input[name='paytype']").on('click', function() {
	paytype = $(this).val();
	console.log(paytype + ' ' + orderid + ' ');
});

/*调起支付*/
function canpay() {
	if(w) {
		return;
	} 
	
	//检查是否请求订单中
	if(paytype == 0) {
		ptype = 'alipay';
		url = webRoot + '/pay/Alipay.php?orderid=' + orderid + '&price=' + money;
	} else if(paytype == 1) {
		ptype = 'wxpay';
		url = webRoot +'/pay/index.php?price=' + money + '&orderid=' + orderid + '&trade_name=' + trade_name;
	}

	w = plus.nativeUI.showWaiting('支付中...', {
		width: '80px',
		height: '80px',
		background: 'rgba(0,0,0,0.3)'
	});
	// 请求支付订单
	var xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function() {
		switch(xhr.readyState) {
			case 4:
				w.close();
				w = null;
				if(xhr.status == 200) {
					var order = xhr.responseText;
//					alert(order);
					plus.payment.request(pays[ptype], order, function(result) {
						toast('支付成功');
						//setSmallchange();/*保存记录，余额不变*/
				}, function(e) {
						console.log("[" + e.code + "]：" + e.message);
					});
				} else {
					plus.nativeUI.toast("获取订单信息失败！");
				}
				break;
			default:
				break;
		}
	}
	xhr.open('get', url);
	xhr.send(); 
}

/*检测*/
function payment() {
	if(!paytype) {
		toast('请选择支付类型');
		return false;
	}

	if(!money) {
		toast('支付金额不正确');
		return false;
	}
	if(!orderid) {
		toast('获取交易单号失败，请刷新页面再试');
		return false;
	}
	canpay(); /*调起第三方支付*/

}
var uName,uTel,uAddress;
window.addEventListener('refresh_address', function(event) {
	uName = event.detail.u_name;
	uTel = event.detail.u_phone;
	uAddress = event.detail.u_address;
	$('#u_name').html(uName);
	$('#u_tel').html(uTel);
	$('#u_address').html(uAddress);
//	alert(uName+"#####"+uTel+"#####"+uAddress);
});


var ws,pay_type,goodsNum;
document.addEventListener("plusready", function() {
	plus.nativeUI.showWaiting();
	ws = plus.webview.currentWebview(); 
	appElement = document.querySelector('[ng-controller=payController]');
	$scope = angular.element(appElement).scope();
	id = ws.goodId;
	orderId = ws.orderId;
	pay_type = ws.pay_type;
	goodsNum = ws.goodsNum;
	if(goodsNum != undefined){
		$('#num').val(goodsNum);
	}
	$('#num').change(function(){
		$('#total_price').html($('#unit_price').html()*$('#num').val());
	})
	setTimeout(function(){	
		$('#total_price').html($('#unit_price').html()*$('#num').val());
	},1000)
	uid = plus.storage.getItem('uid');
	$scope.initView(id, uid);
	$scope.$apply();
	// 获取支付通道
	plus.payment.getChannels(function(channels) {
		for(var i in channels) {
			var channel = channels[i];
			pays[channel.id] = channel;
			checkServices(channel);
		}
	}, function(e) {
		toast("获取支付通道失败：" + e.message);
		outLine("获取支付通道失败：" + e.message);
	});

	// 检测是否安装支付服务 
	function checkServices(pc) {
		if(!pc.serviceReady) {
			var txt = null;
			switch(pc.id) {
				case "alipay":
					txt = "检测到系统未安装“支付宝快捷支付服务”，无法完成支付操作，是否立即安装？";
					break;
				default:
					txt = "系统未安装“" + pc.description + "”服务，无法完成支付，是否立即安装？";
					break;
			}
			plus.nativeUI.confirm(txt, function(e) {
				if(e.index == 0) {
					pc.installService();
				}
			}, pc.description);
		}
	}
}, false)